package com.fgs.common.utils;

import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import java.util.List;

/**
 * @author fgs
 * @date 2020/6/15
 * @description
 **/
public class CommonUtil {

    private static Context context;

    public static void init(Application application) {
        context = application.getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }

    public static float convertDpToPixel(float dp) {
//        Resources resources = context.getResources();
        Resources resources = getContext().getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return px;
    }

    public static float convertPixelsToDp(float px) {
        Resources resources = getContext().getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float dp = px / (metrics.densityDpi / 160f);
        return dp;
    }

    /**
     * 保留两位小数
     *
     * @param string
     * @return
     */
    public static String keepTwoDecimal(String string) {
        try {
            if (!TextUtils.isEmpty(string)) {
                float temp = Float.parseFloat(string);
                return String.format("%.2f", temp);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 保留三位小数
     *
     * @param string
     * @return
     */
    public static String keepThreeDecimal(String string) {
        try {
            if (!TextUtils.isEmpty(string)) {
                float temp = Float.parseFloat(string);
                return String.format("%.3f", temp);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getSelectPictureId(List<String> list) {
        int size = list.size();
        StringBuffer stringBuffer = new StringBuffer();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                stringBuffer.append(list.get(i));
                stringBuffer.append(",");
            }
            String string = stringBuffer.toString();
            return string.substring(0, string.length() - 1);
        } else {
            return "";
        }

    }
}
